package com.tamartech.greendb.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;

import org.apache.log4j.Logger;

import com.Ostermiller.util.CSVParser;
import com.Ostermiller.util.LabeledCSVParser;
import com.tamartech.greendb.data.Address;

// A one-off (I hope) for a messy Redhill West file I received in 2013
public class PostalVoterFilterWest2013
{
    private static Logger logger = Logger.getLogger (PostalVoterFilter.class);
    
    private static String HEAD_ADDRESS1 = "Address1";
    private static String HEAD_ADDRESS2 = "Address2";
    private static String HEAD_ADDRESS3 = "Address3";
    private static String HEAD_ADDRESS4 = "Address4";
    private static String HEAD_ADDRESS5 = "Address5";
    private static String HEAD_ADDRESS6 = "Address6";
    private static String HEAD_FIRST_NAMES = "FirstNames";
    private static String HEAD_SURNAME = "Surname";
    private static String HEAD_VOTE_TYPE = "VoteType";
    private static String HEAD_ELECTION_TYPE = "ElectionType";
    
    private static String POSTAL_VOTE_TYPE = "Postal";
    
    private static String LOCAL_ELECTIONS_ONLY = " Local Only";
    private static String NON_LOCAL_ELECTIONS_ONLY = " Non-Local";

	public static void main(String[] args) throws Exception
	{
        File inFile = new File (args[0] + ".csv");
        File outFile = new File (args[0] + "-mailmerge.csv");
	    
        LabeledCSVParser csv = new LabeledCSVParser (new CSVParser (new FileInputStream (inFile)));
//        csv.changeDelimiter('\t'); // I have commas this year, but apparently it should be tabs
        
        PrintWriter out = new PrintWriter (outFile);
        
        Address curAddress = new Address(); // i.e. initialise to empty one
        String names = "";
        
        while(csv.getLine() != null)
        {
            if (csv.getValueByLabel(HEAD_VOTE_TYPE).trim().contains(POSTAL_VOTE_TYPE) &&
                isPostalLocal (csv.getValueByLabel(HEAD_ELECTION_TYPE).trim()))
//                isPostalNonLocal (csv.getValueByLabel(HEAD_ELECTION_TYPE).trim()))
            {
                String[] addressLines = new String [6];
                addressLines[0] = csv.getValueByLabel(HEAD_ADDRESS1).trim();
                addressLines[1] = csv.getValueByLabel(HEAD_ADDRESS2).trim();
                addressLines[2] = csv.getValueByLabel(HEAD_ADDRESS3).trim();
                addressLines[3] = csv.getValueByLabel(HEAD_ADDRESS4).trim();
                addressLines[4] = csv.getValueByLabel(HEAD_ADDRESS5).trim();
                addressLines[5] = csv.getValueByLabel(HEAD_ADDRESS6).trim();
                
                Address address = createAddress (addressLines);
                
                if (address.equals(curAddress))
                {
                    names += " & " + csv.getValueByLabel(HEAD_FIRST_NAMES).trim().charAt(0) + " " + csv.getValueByLabel(HEAD_SURNAME).trim();
                }
                else
                {
                    if (!names.isEmpty())
                        out.println (createOutLine (names, curAddress));
                    
                    curAddress = address;
                    names = csv.getValueByLabel(HEAD_FIRST_NAMES).trim().charAt(0) + " " + csv.getValueByLabel(HEAD_SURNAME).trim();
                }
            }
        }
        
        if (!names.isEmpty())
            out.println (createOutLine (names, curAddress));

        csv.close();
        out.close();

	}
	
    private static boolean isPostalLocal (String postal)
    {
        return !(NON_LOCAL_ELECTIONS_ONLY.equals(postal));
    }
    
    private static boolean isPostalNonLocal (String postal)
    {
        return !(LOCAL_ELECTIONS_ONLY.equals(postal));
    }
    
    private static String createOutLine (String names, Address address)
    {
        StringBuffer outLine = new StringBuffer();
        
        outLine.append(names + "\t");
        outLine.append(address.getAddress1() + ",");
        outLine.append(address.getAddress2() + ",");
        outLine.append(address.getAddress3() + ",");
        
        return outLine.toString();
    }

    private static Address createAddress (String[] addressLines)
    {
        Address address = new Address();
        
        // reverse through the address to find the last populated line. That will be the postcode
        
        int postcodeIndex = addressLines.length - 1;
        
        for (;;)
        {
            if (postcodeIndex < 0 || addressLines[postcodeIndex].length() > 0)
                break;
                
            postcodeIndex--;
        }
        
        if (postcodeIndex >= 0)
        {
            address.setPostcode (addressLines[postcodeIndex]);
            
            if (postcodeIndex > 0)
                address.setAddress1(addressLines[0]);
            if (postcodeIndex > 1)
                address.setAddress2(addressLines[1]);
            if (postcodeIndex > 2)
                address.setAddress3(addressLines[2]);
            if (postcodeIndex > 3)
                address.setAddress4(addressLines[3]);
            if (postcodeIndex > 4)
                address.setAddress5(addressLines[4]);           
        }
        
        return address;
    }
    
//    public static String toMixed(String input)
//    {
//        StringBuffer buff = new StringBuffer(input.length());
//        boolean isWordStarted = false;
//        for (int i = 0; i < input.length(); i++)
//        {
//            char c = input.charAt(i);
//            if (Character.isLetter(c))
//            {
//                if (isWordStarted)
//                    c = Character.toLowerCase(c);
//                else
//
//                    c = Character.toUpperCase(c);
//                isWordStarted = true;
//            }
//            else
//            {
//                isWordStarted = false;
//            }
//            buff.append(c);
//        }
//        return buff.toString();
//    }
} 